package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.IStatementService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.common.util.file.FileUploadUtils;
import cn.wolfcode.car.common.web.AjaxResult;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.DeploymentBuilder;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.math3.analysis.function.Exp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.zip.ZipInputStream;

@Service
@Transactional
public class BpmnInfoImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;

    @Autowired
    private IStatementService statementService;


    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }


    @Override
    public void save(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public BpmnInfo get(Long id) {
        return bpmnInfoMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.updateByPrimaryKey(bpmnInfo);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            bpmnInfoMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Autowired
    private RuntimeService runtimeService;

    // 删除
    @Override
    public void delete(Long id) {
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(id);
        //1. 删除流程文件
        File file = new File(SystemConfig.getProfile(), bpmnInfo.getBpmnPath());
        if (file.exists()) {
            file.delete();
        }
        // 3:级联删除该流程下启动的所有实例@TODO
        List<ProcessInstance> instances = runtimeService.createProcessInstanceQuery()
                .processInstanceId(bpmnInfo.getActProcessKey())
                .list();

        for (ProcessInstance instance : instances) {
            // 获取business可以-- 通过可以获取serviceItem对象--养修服务套餐对象
            // 2：恢复数据状态---@TODO
        }
        // 删除
        repositoryService.deleteDeployment(bpmnInfo.getDeploymentId(), true);
        // 4: 删除流程定义对象
        bpmnInfoMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<BpmnInfo> list() {
        return bpmnInfoMapper.selectAll();
    }

    // 流程文件上传(二进制)
    @Override
    public AjaxResult upload(MultipartFile file) {
        // 文件上传操作
        // 1> 文件输入流
        // 2> 文件输出流
        if (file != null && file.getSize() > 0) {
            // 上传的文件名
            String filename = file.getOriginalFilename();
            // 判断后缀名
            // xxx.zip --->zip
            // xxx.bpmn --->bpmn
            String ext = FilenameUtils.getExtension(filename);  // 获取后缀名
            if ("zip".equalsIgnoreCase(ext) || "bpmn".equalsIgnoreCase(ext)) {
                //文件上传思考：上传文件存在哪里？
                //springBoot项目最终运行打包jar，图片会导得进去，拿不出来，所以不能把图片直接存在项目里面。
                //一般文件存在硬盘中，然后将路径存在数据库
                //此处存在硬盘中， 当完成部署时候， 在硬盘中数据部署到数据库中
                String upload = null;
                try {
                    // 拼接文件路径
                    upload = FileUploadUtils.upload(SystemConfig.getUploadPath(), file);
                    System.out.println("upload = " + upload);
                } catch (IOException e) {
                    e.printStackTrace();
                    return AjaxResult.error("流程文件上传失败");
                }
                // 上传成功之后返回文件路径
                return AjaxResult.success("上传成功", upload);
            } else {
                return AjaxResult.error("流程定义文件仅支持 bpmn 和 zip 格式！");
            }
        } else {
            return AjaxResult.error("不允许上传空文件！");
        }
    }

    @Autowired
    private RepositoryService repositoryService;

    @Override
    public void deploy(BpmnInfo bpmnInfo) {
        //部署流程
        // 获取扩展名
        String ext = FilenameUtils.getExtension(bpmnInfo.getBpmnPath());
        File file = new File(SystemConfig.getProfile(), bpmnInfo.getBpmnPath());

        DeploymentBuilder builder = repositoryService.createDeployment();

        // 根据后缀名使用不同的处理读取方法
        if ("zip".equalsIgnoreCase(ext)) {
            // zip
            try {

                builder.addZipInputStream(new ZipInputStream(new FileInputStream(file)));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                throw new BusinessException("流程文件部署失败");
            }
        } else if ("bpmn".equalsIgnoreCase(ext)) {
            try {
                builder.addInputStream(bpmnInfo.getBpmnPath(), new FileInputStream(file));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                throw new BusinessException("流程文件部署失败");
            }
        } else {
            throw new BusinessException("流程文件部署失败");
        }
        // 部署
        Deployment deploy = builder.deploy();
        // 创建流程定义对象-自己建表
        if (deploy == null) {
            throw new BusinessException("部署失败");
        }
        // 创建流程定义对象-自己建表
        BpmnInfo newBpmnInfo = new BpmnInfo();
        // 封装数据
        newBpmnInfo.setInfo(bpmnInfo.getInfo());
        newBpmnInfo.setBpmnType(bpmnInfo.getBpmnType());
        newBpmnInfo.setDeploymentId(deploy.getId());
        newBpmnInfo.setDeployTime(deploy.getDeploymentTime());
        newBpmnInfo.setBpmnPath(bpmnInfo.getBpmnPath());

        // activiti7 生成的流程定义表
        // 获取activiti种流程定义对象的：ActProcessId ActProcessKey
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploy.getId())
                .latestVersion()
                .singleResult();

        // 部署对象无法获取name,使用定义对象name(当初或流程图时指定名称)
        newBpmnInfo.setBpmnName(processDefinition.getName());
        newBpmnInfo.setActProcessId(processDefinition.getId());
        newBpmnInfo.setActProcessKey(processDefinition.getKey());
        bpmnInfoMapper.insert(newBpmnInfo);
    }

    // 实现流程文件查看
    @Override
    public InputStream getResoucceByType(String deploymentId, String type) {
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploymentId)
                .latestVersion()
                .singleResult();
        if ("xml".equalsIgnoreCase(type)) {
            return repositoryService.getResourceAsStream(deploymentId, definition.getResourceName());
        } else if ("png".equalsIgnoreCase(type)) {
            BpmnModel model = repositoryService.getBpmnModel(definition.getId());
            DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            InputStream inputStream = generator.generateDiagram(model, Collections.EMPTY_LIST, Collections.EMPTY_LIST,
                    "宋体", "宋体", "宋体");
            return inputStream;

        }
        return null;
    }

    // 查找套餐
    @Override
    public BpmnInfo queryByType(String carPackType) {
        return bpmnInfoMapper.queryByType(carPackType);
    }


}
